package cn.dzz.springcloud.controller;

import cn.dzz.springcloud.component.JsonResult;
import cn.dzz.springcloud.entity.Payment;
import cn.dzz.springcloud.service.PaymentService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author ArkD42
 * @file SpringCloud-ATGG-2020
 * @create 2020年08月24日 21:28
 */
@RestController
@Slf4j
@RequestMapping("payment")
public class PaymentController {

    @Autowired
    private DiscoveryClient discoveryClient;

    @Resource
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    @GetMapping("discovery")
    public Object discovery() {
        List<String> serviceList = discoveryClient.getServices();
        for (String serviceElement : serviceList) {
            log.info("服务元素：" + serviceElement);
        }
        List<ServiceInstance> serviceInstanceList = discoveryClient.getInstances("PROVIDER-PAYMENT-SERVICE");
        for (ServiceInstance serviceInstance : serviceInstanceList) {
            log.info(
                "服务实例ID " + serviceInstance.getServiceId() +
                "\t 服务主机地址 " + serviceInstance.getHost() +
                "\t 服务端口 " + serviceInstance.getPort() +
                "\t URI地址" + serviceInstance.getUri()
            );
        }
        return this.discoveryClient;
    }

    @PostMapping("create")
    public JsonResult<Object> createPayment(@RequestBody Payment payment){
        int result = paymentService.addPayment(payment);
        log.info("插入操作结果：" + result);
        if (result > 0) return new JsonResult<Object>(200, "插入数据成功, 端口：" + serverPort, result);
        return new JsonResult<Object>(500, "插入数据失败 端口：" + serverPort, result);
    }
    @GetMapping("get/{id}")
    public JsonResult<Payment> getPaymentById(@PathVariable("id") Long id){
        Payment paymentById = paymentService.getPaymentById(id);
        log.info("查询操作结果：" + paymentById + "用来测试热部署的修改");
        if (paymentById != null) return new JsonResult<Payment>(200, "查询数据成功  端口：" + serverPort, paymentById);
        return new JsonResult<Payment>(500, "查询数据失败  端口：" + serverPort, null);
    }
}
